Selection Sort in Java

Course- Java >

We can create a java program to sort array elements using selection sort. In selection sort algorithm, we search for the lowest element and arrange it to the proper location. We swap the current element with the next lowest number.

selection sort

 
  1. public class SelectionSortExample {  
  2.     public static void selectionSort(int[] arr){  
  3.         for (int i = 0; i < arr.length - 1; i++)  
  4.         {  
  5.             int index = i;  
  6.             for (int j = i + 1; j < arr.length; j++){  
  7.                 if (arr[j] < arr[index]){  
  8.                     index = j;//searching for lowest index  
  9.                 }  
  10.             }  
  11.             int smallerNumber = arr[index];   
  12.             arr[index] = arr[i];  
  13.             arr[i] = smallerNumber;  
  14.         }  
  15.     }  
  16.        
  17.     public static void main(String a[]){  
  18.         int[] arr1 = {9,14,3,2,43,11,58,22};  
  19.         System.out.println("Before Selection Sort");  
  20.         for(int i:arr1){  
  21.             System.out.print(i+" ");  
  22.         }  
  23.         System.out.println();  
  24.           
  25.         selectionSort(arr1);//sorting array using selection sort  
  26.          
  27.         System.out.println("After Selection Sort");  
  28.         for(int i:arr1){  
  29.             System.out.print(i+" ");  
  30.         }  
  31.     }  
  32. }  

Output:

Before Selection Sort
9 14 3 2 43 11 58 22 
After Selection Sort
2 3 9 11 14 22 43 58